//
//  GLESCapture.m
//  FrameBufferObject
//
//  Created by 畑圭輔 on 10/03/23.
//  Copyright 2010 Keisuke Hata. All rights reserved.
//

#import "GLESCapture.h"


@implementation GLESCapture

+ (UIImage *) snapShotFrameBuffer : (GLuint)fbo 
						frameWidth:(NSInteger)width
					   frameHeight:(NSInteger)height {

	GLint oldFBO;
	
	// FrameBufferにattach
	glPushMatrix();
	
	float backingWidth  = width; 
	float backingHeight = height; 
	
    glViewport(0, 0, backingWidth, backingHeight);
	glOrthof( 0,backingWidth, backingHeight, 0, -1, 1 );

	// 以前のフレームバッファを取得
	glGetIntegerv(GL_FRAMEBUFFER_BINDING_OES, &oldFBO);
    glBindFramebufferOES(GL_FRAMEBUFFER_OES, fbo);

	int tx = width;
	int ty = height;
	
	int bitsPerComponent	= 8;
	int bitsPerPixel		= 32;
	int bytesPerPixel		= (bitsPerComponent * 4)/8;
	int bytesPerRow			= bytesPerPixel * tx;
	NSInteger bufferLength	= bytesPerRow * ty;
	
	NSMutableData *buffer	= [[NSMutableData alloc] initWithCapacity:bufferLength];
	NSMutableData *pixels	= [[NSMutableData alloc] initWithCapacity:bufferLength];
	
	if( ! (buffer && pixels) ) {
		[buffer release];
		[pixels release];
		return nil;
	}
	
	// ピクセルデータをコピー
	glReadPixels(0,0,tx,ty,GL_RGBA,GL_UNSIGNED_BYTE, [buffer mutableBytes]);

	// 以前のフレームバッファに設定し直し
	glBindFramebufferOES(GL_FRAMEBUFFER_OES, oldFBO);
	
	// RGBAの画像データに変換
	CGBitmapInfo bitmapInfo			= kCGImageAlphaPremultipliedLast | kCGBitmapByteOrderDefault;
	CGDataProviderRef provider		= CGDataProviderCreateWithData(NULL, [buffer mutableBytes], bufferLength, NULL);
	CGColorSpaceRef colorSpaceRef	= CGColorSpaceCreateDeviceRGB();
	CGImageRef imageRef				= CGImageCreate(tx, 
													ty,
													bitsPerComponent, 
													bitsPerPixel, 
													bytesPerRow,
													colorSpaceRef, 
													bitmapInfo, 
													provider,
													NULL, 
													false/* readonlyデータ */, 
													kCGRenderingIntentDefault);
	CGContextRef context = CGBitmapContextCreate([pixels mutableBytes], 
												tx,
												ty, 
												CGImageGetBitsPerComponent(imageRef), 
												CGImageGetBytesPerRow(imageRef),
												CGImageGetColorSpace(imageRef), 
												bitmapInfo
												);
	// Quartzの座標系に変換
	CGContextTranslateCTM(context, 0.0f, ty);
	CGContextScaleCTM(context, 1.0f, -1.0f);
	CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, tx, ty), imageRef);   
	CGImageRef outputRef = CGBitmapContextCreateImage(context);
	UIImage* image		 = [[UIImage alloc] initWithCGImage:outputRef];
	
	CGImageRelease(imageRef);
	CGContextRelease(context);
	CGColorSpaceRelease(colorSpaceRef);
	CGDataProviderRelease(provider);
	CGImageRelease(outputRef);
	
	[pixels release];
	[buffer release];
	
	return [image autorelease];
}

@end
